package com.example.weight.greenSeasons.waterDeal;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.navigation.SijiqingFlocculationNavActivity;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class ErrorRecordTable extends AppCompatActivity implements View.OnClickListener{
    private TitleBar titleBar;
//    设备名称
    private EditText fault_description,maintainer,failure_cause_analysis,maintenance_method,inspector;
    private TextView failure_date,recovery_date;
    private TextView device_name;
//    private TextView recovery_time;
//操作人
    private String name, factory;
    private EditText operator;
    DateFormat format= DateFormat.getDateTimeInstance();
    Calendar calendar= Calendar.getInstance(Locale.CHINA);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_error_record_table);

        titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                ErrorRecordTable.this.finish();
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {

            }


        });
//        设备名称
        device_name = (TextView) findViewById(R.id.device_name);
//        故障描述
        fault_description = (EditText) findViewById(R.id.fault_description);
//        维修人员名字
        maintainer = (EditText) findViewById(R.id.maintainer);
//        故障发生原因分析
        failure_cause_analysis = (EditText) findViewById(R.id.failure_cause_analysis);
//        维修方法
        maintenance_method = (EditText) findViewById(R.id.maintenance_method);
//        检查人
        inspector = (EditText) findViewById(R.id.inspector);
//        故障发生时间
        failure_date = (TextView) findViewById(R.id.failure_date);
        failure_date.setOnClickListener(this);
//        故障恢复时间
        recovery_date = (TextView) findViewById(R.id.recovery_date);
        recovery_date.setOnClickListener(this);

        //操作人
        //用户和职责
        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");

        operator=findViewById(R.id.operator);
        operator.setText(name);
        operator.setFocusableInTouchMode(false);
//        repair_time = (TextView) findViewById(R.id.repair_time);
//        repair_time.setOnClickListener(this);
//        recovery_time = (TextView) findViewById(R.id.recovery_time);
//        recovery_time.setOnClickListener(this);

    }

    /**
     * 日期选择
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    @SuppressLint("ResourceType")
    public static void showDatePickerDialog(Activity activity, int themeResId, final TextView tv, Calendar calendar) {
        // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
        new DatePickerDialog(activity, themeResId, new DatePickerDialog.OnDateSetListener() {
            // 绑定监听器(How the parent is notified that the date is set.)
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 此处得到选择的时间，可以进行你想要的操作
                tv.setText(year + "年" + (monthOfYear + 1) + "月" + dayOfMonth + "日");
            }
        }
                // 设置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();
    }
    /**
     * 时间选择
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public static void showTimePickerDialog(Activity activity,int themeResId, final TextView tv, Calendar calendar) {
        // Calendar c = Calendar.getInstance();
        // 创建一个TimePickerDialog实例，并把它显示出来
        // 解释一哈，Activity是context的子类
        new TimePickerDialog( activity,themeResId,
                // 绑定监听器
                new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        tv.setText(String.format("%02d", hourOfDay) + ":" + String.format("%02d", minute));
                    }
                }
                // 设置初始时间
                , calendar.get(Calendar.AM_PM)
                , calendar.get(Calendar.MINUTE)
                // true表示采用24小时制
                ,true).show();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.failure_date:
                chooseStopDate(this,  failure_date);
                break;
            case R.id.recovery_date:
                chooseStopDate(this,  recovery_date);
                break;
//            case R.id.repair_time:
//                showTimePickerDialog(this,  2, repair_time, calendar);
//                break;
//            case R.id.recovery_time:
//                showTimePickerDialog(this,  2, recovery_time, calendar);
//                break;
            default:
                break;
        }
    }
    /**
     * 提交内容并设置输入缓存
     * @param view
     */
    public void save(View view) {
        if (device_name.getText().toString().equals("")) {
            Toast.makeText(this, "请输入故障设备名称", Toast.LENGTH_SHORT).show();
            return;
        }
        if (failure_date.getText().toString().equals("点击选择时间")||failure_date.getText().toString().equals("")) {
            Toast.makeText(this, "请选择故障发生时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (fault_description.getText().toString().equals("")) {
            Toast.makeText(this, "请输入故障情况描述", Toast.LENGTH_SHORT).show();
            return;
        }
        if (maintainer.getText().toString().equals("")) {
            Toast.makeText(this, "请输入维修人员名字", Toast.LENGTH_SHORT).show();
            return;
        }
        if (failure_cause_analysis.getText().toString().equals("")) {
            Toast.makeText(this, "请输入故障原因分析", Toast.LENGTH_SHORT).show();
            return;
        }
        if (maintenance_method.getText().toString().equals("")) {
            Toast.makeText(this, "请输入维修方法", Toast.LENGTH_SHORT).show();
            return;
        }
        if (inspector.getText().toString().equals("")) {
            Toast.makeText(this, "请输入检查人姓名", Toast.LENGTH_SHORT).show();
            return;
        }

        if (recovery_date.getText().toString().equals("点击选择时间")||failure_date.getText().toString().equals("")) {
            Toast.makeText(this, "请选择故障恢复时间", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {
                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/sjq/SjqWaterProductionFailure/addForm";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Toast.makeText(ErrorRecordTable.this, "保存成功", Toast.LENGTH_SHORT).show();
                                    Log.d("jy", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.startsWith("2"))
                                            Toast.makeText(ErrorRecordTable.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(ErrorRecordTable.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(ErrorRecordTable.this,
                                    "保存失败" + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("equipment_name", device_name.getText().toString());
                            map.put("failure_reason", failure_cause_analysis.getText().toString());
                            map.put("maintenance_method", maintenance_method.getText().toString());
                            map.put("recovery_time",recovery_date.getText().toString());
                            map.put("examiner", inspector.getText().toString());
                            map.put("down_time", failure_date.getText().toString());
                            map.put("operate_person", operator.getText().toString());
                            map.put("repair_person", maintainer.getText().toString());
                            map.put("failure_description", fault_description.getText().toString());
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }

    @SuppressLint({"DefaultLocale", "ResourceType"})
    public void chooseStopDate(Activity activity,final TextView tv) {

        int YEAR = calendar.get(Calendar.YEAR);
        int MONTH = calendar.get(Calendar.MONTH);
        int DAY = calendar.get(Calendar.DAY_OF_MONTH);
        int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
        int MINUTE = calendar.get(Calendar.MINUTE);
        new DatePickerDialog(this, 2, (view1, year, month, day) -> {
            // 更新EditText控件日期 小于10加0
            new TimePickerDialog(this, 2, (view11, hourOfDay, minute) -> {
                //  这个方法是得到选择后的 小时、分钟，分别对应着三个参数 —   hourOfDay、minute
                tv.setText(new StringBuilder()
                        .append(year)
                        .append("/")
                        .append((month + 1) < 10 ? "0"
                                + (month + 1) : (month + 1))
                        .append("/")
                        .append((day < 10) ? "0" + day : day)
                        .append(" ")
                        .append(String.format("%02d",hourOfDay))
                        .append(":")
                        .append(String.format("%02d",minute)));
            },
                    HOUR, MINUTE, true).show();
        },
                YEAR, MONTH, DAY).show();
    }

}